import { defineStore } from 'pinia';
import { MessagePlugin } from 'tdesign-vue-next';
import { nextTick } from 'vue';
import { TOKEN_NAME, TOKEN_TEAM } from '@/config/global';
import { store, useConstantsStore, useTabsRouterStore, getPermissionStore } from '@/store';
import {
  apiUsersHeartbeat,
  apiUsersLogin,
  apiUsersLogout,
  apiUsersLoginTeam,
  apiSelectsGetTeams,
} from '@/api/model/rapToTs/gMVdesk';
import { getItem, getItemFromSession, setItem, setItemToSession } from '@/utils/storage';
import { axiosHandleError } from '@/utils/request/utils';

// 添加必要的类型定义
interface Team {
  id: number;
  [key: string]: any;
}

interface UserInfo {
  name: string;
  email: string;
  phone: string;
  team: Team;
  roles: string[] | null;
  role: string;
  active_token: string;
  id: string;
}

// 扩展 Window 接口
declare global {
  interface Window {
    HeartBeatTimer: number | null;
    isLoginErrorMsg: boolean;
  }
}

// 角色权限映射
const roleMap: Record<string, string[]> = {
  team_operator: ['AdvertReport', 'orderReport', 'login', 'GoodsList', 'AccountList', 'LinksList', 'BackhaulAlocation'],
  team_manager: ['AdvertReport', 'orderReport', 'login', 'GoodsList', 'AccountList', 'ProjectList', 'LinksList', 'BackhaulAlocation'],
  administrator: ['admin', 'BackhaulAlocation'],
};

// 初始用户信息
const InitUserInfo: UserInfo = {
  name: '',
  email: '',
  phone: '',
  team: { id: 0 },
  roles: null,
  role: '',
  active_token: '',
  id: '',
};

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: InitUserInfo as UserInfo,
    allTeams: [] as Team[],
  }),

  getters: {
    roles: (state) => state.userInfo?.roles,
  },

  actions: {
    // 登录相关方法
    async login(userInfo: Record<string, any>) {
      return new Promise<boolean>((resolve) => {
        apiUsersLogin({ ...userInfo }).then((res: any) => {
          if (res.code === 0) {
            const { token, ...resetInfo } = res.data;
            this.token = token;
            this.userInfo = { ...resetInfo };
            resolve(true);
          } else {
            axiosHandleError(res.msg);
            resolve(false);
          }
        });
      });
    },

    // 获取用户权限
    async getUserInfo() {
      let authorityRoles = roleMap[this.userInfo.role] || [];
      
      if (this.userInfo.team?.id !== 1 && this.userInfo.team?.id !== 13) {
        authorityRoles = authorityRoles.filter(role => role !== 'BackhaulAlocation');
      }

      this.userInfo = {
        ...this.userInfo,
        roles: authorityRoles,
      };
    },

    // Token 相关方法
    saveToken(getItemFunc: Function, setItemFunc: Function) {
      let localTeam: any[] = JSON.parse(getItemFunc(TOKEN_TEAM) || '[]');
      const userInfoWithTeam = { ...this.userInfo.team, userId: this.userInfo.id };

      if (Array.isArray(localTeam)) {
        const existingUserIndex = localTeam.findIndex(item => item.userId === userInfoWithTeam.userId);
        if (existingUserIndex !== -1) {
          localTeam[existingUserIndex] = userInfoWithTeam;
        } else {
          localTeam.push(userInfoWithTeam);
        }
      } else {
        localTeam = [userInfoWithTeam];
      }

      setItemFunc(TOKEN_NAME, JSON.stringify({ token: this.token, userInfo: this.userInfo }));
      setItemFunc(TOKEN_TEAM, JSON.stringify(localTeam));
    },

    // 团队相关方法
    async changeTeam(team: Team) {
      return new Promise((resolve) => {
        this.userInfo = { ...this.userInfo, team };
        this.loginTeam({ teamId: team.id }, (res: any) => {
          if (res) {
            getPermissionStore().restore();
            this.saveTokenToLocalStorage();
            nextTick(() => resolve(res));
          }
        });
      });
    },

    // 登出
    async logout() {
      try {
        await apiUsersLogout();
        if (window.HeartBeatTimer) {
          clearTimeout(window.HeartBeatTimer);
          window.HeartBeatTimer = null;
        }
        
        [TOKEN_NAME, 'customTemplate'].forEach(key => {
          localStorage.removeItem(key);
          sessionStorage.removeItem(key);
        });

        useTabsRouterStore().removeTabRouterList();
        this.token = '';
        this.userInfo = InitUserInfo;
        window.location.reload();
      } catch (e) {
        axiosHandleError(e);
      }
    },

    async removeToken() {
      this.token = '';
    },
    
    saveTokenToLocalStorage() {
      this.saveToken(getItem, setItem);
    },

    saveTokenToSessionStorage() {
      this.saveToken(getItemFromSession, setItemToSession);
    },

    getTokenfromLocal() {
      let localInfo = getItem(TOKEN_NAME) || getItemFromSession(TOKEN_NAME);
      if (localInfo) {
        localInfo = JSON.parse(localInfo);
        console.log('userInfoFromLocal', localInfo);

        // eslint-disable-next-line dot-notation
        if (localInfo['token']) {
          // eslint-disable-next-line dot-notation
          this.token = localInfo['token'];
          // eslint-disable-next-line dot-notation
          this.userInfo = { ...localInfo['userInfo'] };
          // 发送心跳包
          loginSuccess();
        }
      }
    },
    saveteam({ teamId, allTeams }, { role, active_token }) {
      if (!allTeams || allTeams.length === 0) {
        allTeams = this.allTeams;
      }
      // eslint-disable-next-line no-unsafe-optional-chaining
      const [team] = allTeams?.filter((item) => item.id === teamId);
      console.log({ team, teamId });
      this.userInfo = { ...this.userInfo, team, role, active_token };
      this.allTeams = allTeams;
    },
    async getAllTeam() {
      try {
        const res = await apiSelectsGetTeams();
        if (res.code == 0) {
          this.allTeams = res.data.rows;
        } else {
          throw res.msg;
        }
      } catch (e) {
        axiosHandleError(e);
      }
    },
    async loginTeam({ teamId, allTeams = [] }, callback) {
      console.log('loginTeam1', teamId);
      const userStore = useUserStore();
      const res = await apiUsersLoginTeam({ team_id: teamId });
      if (res.code == 0) {
        console.log('loginTeam2', teamId);
        userStore.saveteam({ teamId, allTeams }, res.data);
        loginSuccess();
        callback?.('success');
      } else {
        MessagePlugin.error('登录失败，请重试');
        callback?.('error');
      }
    },
  },
});

// 心跳检测相关
function runTimer(fn: () => void) {
  const inner = () => {
    window.HeartBeatTimer = window.setTimeout(() => {
      fn();
      if (window.HeartBeatTimer) clearTimeout(window.HeartBeatTimer);
      inner();
    }, 60000);
  };
  inner();
}

// 登录成功后的处理
function loginSuccess() {
  MessagePlugin.closeAll();
  window.isLoginErrorMsg = false;
  sendHeartBeat();
  
  const constantsStore = useConstantsStore();
  constantsStore.getConstants();
  useUserStore().getAllTeam();
}

export function getUserStore() {
  return useUserStore(store);
}

// 发送心跳包 code非0时logout
function sendHeartBeat() {
  if (!window.HeartBeatTimer) {
    console.log('init heart');
    timer();
  }
  function timer() {
    runTimer(async () => {
      try {
        const res = await apiUsersHeartbeat();
        if (res.code !== 0) {
          throw res.msg;
        }
      } catch (e) {
        console.log('heartbeat error', e);
        const user = useUserStore();
        user.logout();
        axiosHandleError(e);
      }
    });
  }
}
